package cn.swust.service.serviceimpl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import cn.swust.model.AdminBean;
import cn.swust.service.AdminService;
import cn.swust.util.DBUtil;

public class AdminServiceImpl implements AdminService{

	public int addAdmin(AdminBean admin) {
		int ret = 0;
		try{
		String insertSql = "insert into admin(admin_name,admin_password,admin_chname,admin_nickname)" +
		" values ('" + admin.getName() + "','" + admin.getPassword() + "','" + 
		admin.getChname() + "','" + admin.getNickname() + "')";
		Connection conn = DBUtil.getConnection();
		Statement state = conn.createStatement();
		state.execute(insertSql, Statement.RETURN_GENERATED_KEYS);
		ResultSet rs = state.getGeneratedKeys();
		while(rs.next())
			ret = rs.getInt(1);
		} catch (SQLException e) {
			e.printStackTrace();
		} 
		return ret;
	}

	public int delAdmin(int id) {
		String delSql = "delete from admin where admin_id =" + id;
		return DBUtil.updateSql(delSql);
	}

	public int modAdmin(int id, AdminBean admin) {
		String modSql = "update admin set admin_name = '" +admin.getName() + "',admin_password = '" +
		admin.getPassword() + "',admin_chname = '" + admin.getChname() + "',admin_nickname = '" +
		admin.getNickname() + "' where admin_id = " + id;
		return DBUtil.updateSql(modSql);
	}

	public AdminBean queryById(int id) {
		String querySql = "select * from admin where admin_id = " +  id;
		ResultSet rs = DBUtil.querySql(querySql, DBUtil.creatStatement(DBUtil.getConnection()));
		AdminBean aBean = new AdminBean();
		try {
			while(rs.next()){
				aBean.setId(rs.getInt("admin_id"));
				aBean.setName(rs.getString("admin_name"));
				aBean.setPassword(rs.getString("admin_password"));
				aBean.setChname(rs.getString("admin_chname"));
				aBean.setNickname(rs.getString("admin_nickname"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return aBean;
	}

	public AdminBean queryByName(String name) {
		String querySql = "select * from admin where admin_name = '" + name + "'";
		ResultSet rs = DBUtil.querySql(querySql, DBUtil.creatStatement(DBUtil.getConnection()));
		AdminBean aBean = new AdminBean();
		try {
			while(rs.next()){
				aBean.setId(rs.getInt("admin_id"));
				aBean.setName(rs.getString("admin_name"));
				aBean.setPassword(rs.getString("admin_password"));
				aBean.setChname(rs.getString("admin_chname"));
				aBean.setNickname(rs.getString("admin_nickname"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return aBean;
	}

}
